﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using System.Configuration;
using BreadWebAPI.Models;

namespace BreadWebAPI.Controllers
{
    public class CommentsController : ApiController
    {
        CloudStorageAccount storageAccount;
        CloudTable table;

        public CommentsController()
        {
            // need to make this code execute only once
            storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            table = tableClient.GetTableReference("Comments");

        }

        // GET api/comments, return today's comments
        public IEnumerable<CommentsEntity> Get([FromUri]string BreadDate)
        {
            if (String.IsNullOrEmpty(BreadDate))
                return null;

            // BreadDate looks like "2015-01-08"
            string partitionkeyYear = BreadDate.Substring(0, 4);
            string partitionkeyDate = BreadDate.Replace("-", "");
            string filter = String.Format("(PartitionKey eq '{0}' or PartitionKey eq '{1}') and BreadUrl eq '{2}'", 
                                            partitionkeyYear, partitionkeyDate, BreadDate);
            
            // Create the table query.
            TableQuery<CommentsEntity> query = new TableQuery<CommentsEntity>().Where(filter);
            IEnumerable<CommentsEntity> result = table.ExecuteQuery(query);

            // sort by timestamp before we return
            result = from item in result
                     orderby item.Timestamp descending
                     select item;

            return result;
        }

        // GET api/comments/2012-10-05
        //public IEnumerable<CommentsEntity> Get(string anotherDay)
        //{

        //    // Create the table query.
        //    TableQuery<CommentsEntity> query = new TableQuery<CommentsEntity>().Where(
        //            TableQuery.GenerateFilterCondition("BreadUrl", QueryComparisons.Equal, anotherDay));

        //    return table.ExecuteQuery(query);
        //}

        // POST api/comments
        public void Post([FromBody]CommentsEntity value)
        {
            try
            {
                // Create the TableOperation that inserts the comment entity.
                TableOperation insertOperation = TableOperation.Insert(value);

                // Execute the insert operation.
                TableResult tr = table.Execute(insertOperation);
                
                //var response = Request.CreateResponse<CommentsEntity>(HttpStatusCode.Created, value);

                //string uri = Url.Link("DefaultApi", new { id = item.Id });
                //response.Headers.Location = new Uri(uri);
                //return response;
            }
            catch (Exception ex)
            {
                  var errorResponse = new HttpResponseMessage();
                  errorResponse.StatusCode = HttpStatusCode.NotFound;
                  errorResponse.Content = new StringContent(ex.ToString());
                  throw new HttpResponseException(errorResponse);
            }
        }

        // PUT api/comments/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/comments/5
        public void Delete(int id)
        {
        }
    }
}
